<?php

namespace yunj\library\traits;

trait Redis {

    /**
     * @var \Redis
     */
    protected $redis;

    /**
     * 获取redis连接回调
     * @var callable
     */
    protected $redisConnCall;

    /**
     * redis获取
     * @return \Redis
     */
    public function getRedis(): \Redis {
        if (!$this->redis) {
            $this->setRedis();
        }
        return $this->redis;
    }

    /**
     * @param \Redis|null $redis
     * @return static
     */
    protected function setRedis() {
        $redisConnCall = $this->redisConnCall?:function(){
            $redis = new \Redis();
            $redis->connect("127.0.0.1", 6379);
            return $redis;
        };
        $this->redis = $redisConnCall();
        // 判断连接是否成功，不成功会抛异常
        $this->redis->ping();
        return $this;
    }

    /*
     * 设置获取redis连接的回调方法
     * @param callable $call
     * @return static
     */
    public function setRedisConnCall(callable $call){
        $this->redisConnCall = $call;
        return $this;
    }
}